//
//  CachingKey+Moya.swift
//  XNetwork_Example
//
//  Created by x on 2024/8/9.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import Moya

/// 实现缓存的key
extension StoringKey where Self: TargetType {
    public var stringValue: String {
        return cachedKey
    }
}

private extension TargetType {
    
    var endpoint: Endpoint {
        return Endpoint(url: URL(target: self).absoluteString, sampleResponseClosure: { .networkResponse(200, self.sampleData)}, method: method, task: task, httpHeaderFields: headers)
    }
    
    var cachedKey: String {
        
        if let urlRequest = try? endpoint.urlRequest(),
           let data = urlRequest.httpBody,
           let parameters = String(data: data, encoding: .utf8) {
            return "\(method.rawValue):\(endpoint.url)?\(parameters)"
        }
        
        return "\(method.rawValue):\(endpoint.url)"
    }
}

